package cn.dhnep.demo.controller;


import cn.dhnep.demo.pojo.Admin;
import cn.dhnep.demo.pojo.Menu;
import cn.dhnep.demo.pojo.Notice;
import cn.dhnep.demo.service.HomepageService;
import cn.dhnep.demo.util.Constant;
import cn.dhnep.demo.util.MenuTree;
import cn.dhnep.demo.util.Page;
import cn.dhnep.demo.util.ResultMap;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 主页功能controller
 * </p>
 *
 * @author dhn
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/homepage")
public class HomepageController {


    @Resource
    private HomepageService homepageService;

    private Map<String, Object> result = new HashMap<>();

    @ApiOperation("用户统计")
    @GetMapping("usercount")
    public int Usercount(HttpServletRequest request) {
        int count = homepageService.usercount();
        return count;
    }

    @ApiOperation("骑手统计")
    @GetMapping("horsemancount")
    public int Horsemancount(HttpServletRequest request) {
        int count = homepageService.horsemancount();
        return count;
    }

    @ApiOperation("订单统计")
    @GetMapping("ordercount")
    public int Ordercount(HttpServletRequest request) {
        int count = homepageService.ordercount();
        return count;
    }

    @ApiOperation("商家统计")
    @GetMapping("merchantcount")
    public int Merchantcount(HttpServletRequest request) {
        int count = homepageService.merchantcount();
        return count;
    }

    @ApiOperation("系统公告查询")
    @GetMapping("selectNotice")
    public List<Notice> SelectNotice(HttpServletRequest request) {
        List<Notice> notice = homepageService.selectNotice();
        return notice;
    }


    @ApiOperation("session方法")
    @GetMapping("SessionMap")
    public Map<String, Object> SessionMap(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Admin a = (Admin) session.getAttribute(Constant.USER_SESSION);
        result.put("loginname", a.getAdminNickname());
        return result;
    }

    @ApiOperation("系统公告分页查询")
    @RequestMapping("noticelist")
    public ResultMap<List<Notice>> NoticeList(String title, Page page, @RequestParam("limit") Integer limit) throws UnsupportedEncodingException {
        page.setRows(limit);
        if (title != null) {
            page.setTitle(title);
        }
        List<Notice> contentList = homepageService.selectPageList(page);
        int totals = homepageService.selectPageCount(page);
        page.setTotalRecord(totals);

        return new ResultMap<List<Notice>>("", contentList, 0, totals);
    }

    @ApiOperation("系统公告发布")
    @RequestMapping("noticeadd")
    public Map<String, Object> Noticeadd(HttpServletRequest request, String title, String content) {
        Notice notice = new Notice();
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute(Constant.USER_SESSION);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        notice.setTitle(title);
        notice.setContent(content);
        notice.setTime(df.format(new Date()));
        notice.setName(admin.getAdminNickname());
        int count = homepageService.onticeadd(notice);
        if (count == 1) {
            result.put("result", "success");
        } else {
            result.put("result", "error");
        }
        return result;
    }

    @ApiOperation("删除系统公告")
    @RequestMapping("noticedelete")
    public Map<String, Object> Noticedelete(HttpServletRequest request, int id) {
        System.out.println(id);
        int count = homepageService.onticedelete(id);
        if (count == 1) {
            result.put("result", "success");
        } else {
            result.put("result", "error");
        }
        return result;
    }

    @ApiOperation("用户曲线图")
    @GetMapping("selectuser")
    public List<Map<String, Object>> selectuser() {

        List<Map<String, Object>> userList = homepageService.usercurve();
        List<Map<String, Object>> horsemanList = homepageService.horsemancurve();
        List<Map<String, Object>> orderList = homepageService.ordercurve();
        List<Map<String, Object>> List = new ArrayList<>();
        List.addAll(userList);
        List.addAll(horsemanList);
        List.addAll(orderList);
        System.out.println("List+" + List);
        JSONArray json = JSONArray.fromObject(List);
        System.out.println("用户曲线图:" + json);
        return json;
    }

    @ApiOperation("曲线图时间")
    @GetMapping("curvedate")
    public List<String> curvedate() {
        List<String> curvedateList = homepageService.datacurve();
        JSONArray json = JSONArray.fromObject(curvedateList);
        System.out.println(json);
        return json;
    }

    /**
     * 废弃，请勿使用！写入init.json会覆盖！
     */
    @ApiOperation("菜单栏")
    @GetMapping("Menu")
    public void menu() throws IOException {
        List<Menu> menuList = homepageService.menyList();
        MenuTree menuTree = new MenuTree(menuList);
        menuList = menuTree.builTree();
        String jsonOutput = JSON.toJSONString(menuList);
        System.out.println(jsonOutput);
        writeResource(jsonOutput);
    }

    public void writeResource(String json) throws IOException {
        //创建文件，若存在则读取已有的
		/*ClassPathResource classPathResource = new ClassPathResource("static/api/init.json");
		File file = classPathResource.getFile();*/

        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath);
        File f1 = new File(projectPath + "/src/main/resources/static/api/init.json");
        //根据指定文件路径构建文件输出流对象
        FileOutputStream fos = new FileOutputStream(f1);
        String str1 = null;
        try {
            //将json文件转为string类型，进行写入
            str1 = JSON.toJSONString(json);
            System.out.println("打印转String：" + str1);
            System.out.println("打印原json：" + json);

        } catch (Exception e) {
            e.printStackTrace();
        }
        fos.write(json.getBytes()); // 把对象信息写入文件
    }


}

